package com.lagou.util;

import com.google.common.cache.Cache;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

public class ResponseStatisticsUtil {

    private static Map<String, Cache<String, Long>> map = new ConcurrentHashMap();

    public static void saveMethodResponse(String methodName, long responseTime) {
        Cache<String, Long> cache = getMethodResponseCache(methodName);
        cache.put(UUID.randomUUID().toString(), responseTime);
    }

    public static Cache<String, Long> getMethodResponseCache(String methodName) {
        Cache<String, Long> cache = null;
        if (!map.containsKey(methodName)) {
            synchronized (ResponseStatisticsUtil.class) {
                if (!map.containsKey(methodName)) {
                    map.putIfAbsent(methodName, LocalCacheUtil.getDefaultCache());
                }
            }
        }
        cache = map.get(methodName);
        return cache;
    }

    public static long getMethodResponseTp(String method, double tpValue) {
        Cache<String, Long> cache = getMethodResponseCache(method);
        ConcurrentMap<String, Long> concurrentMap = cache.asMap();

        ArrayList<Long> values = new ArrayList<>(concurrentMap.values());
        if (values.isEmpty()) {
            return 0;
        }
        List<Long> collect = values.stream().sorted().collect(Collectors.toList());
        int index = (int) ((int) collect.size() * tpValue);
        Long responseTime = collect.get(index);
        return responseTime;
    }

    public static void main(String[] args) {
        System.out.println((int) (100 * 0.89));
    }


}
